/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.home.modular.structure.user.service.impl;

import cn.afterturn.easypoi.cache.manager.POICacheManager;
import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fhs.trans.service.impl.TransService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.home.core.enums.HomeBuildInEnum;
import vip.xiaonuo.home.core.enums.HomeDataTypeEnum;
import vip.xiaonuo.home.modular.structure.org.entity.HomeOrg;
import vip.xiaonuo.home.modular.structure.org.service.HomeOrgService;
import vip.xiaonuo.home.modular.structure.position.entity.HomePosition;
import vip.xiaonuo.home.modular.structure.position.service.HomePositionService;
import vip.xiaonuo.home.modular.structure.relation.entity.HomeRelation;
import vip.xiaonuo.home.modular.structure.relation.enums.HomeRelationCategoryEnum;
import vip.xiaonuo.home.modular.structure.relation.service.HomeRelationService;
import vip.xiaonuo.home.modular.structure.resource.entity.HomeButton;
import vip.xiaonuo.home.modular.structure.resource.entity.HomeMenu;
import vip.xiaonuo.home.modular.structure.resource.service.HomeButtonService;
import vip.xiaonuo.home.modular.structure.resource.service.HomeMenuService;
import vip.xiaonuo.home.modular.structure.role.entity.HomeRole;
import vip.xiaonuo.home.modular.structure.role.service.HomeRoleService;
import vip.xiaonuo.home.modular.structure.user.entity.HomeUser;
import vip.xiaonuo.home.modular.structure.user.enums.HomeRoleCategoryEnum;
import vip.xiaonuo.home.modular.structure.user.enums.HomeUserStatusEnum;
import vip.xiaonuo.home.modular.structure.user.mapper.HomeUserMapper;
import vip.xiaonuo.home.modular.structure.user.param.*;
import vip.xiaonuo.home.modular.structure.user.result.HomeUserExportResult;
import vip.xiaonuo.home.modular.structure.user.result.HomeUserOwnResourceResult;
import vip.xiaonuo.home.modular.structure.user.result.HomeUserRoleResult;
import vip.xiaonuo.home.modular.structure.user.service.HomeUserService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.excel.CommonExcelCustomMergeStrategy;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.util.*;
import vip.xiaonuo.dev.api.DevConfigApi;
import vip.xiaonuo.sys.api.SysRoleApi;
import vip.xiaonuo.sys.api.SysUserApi;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 人员Service接口实现类
 *
 * @author xuyuxiang
 * @date 2022/2/23 18:43
 **/
@Service
public class HomeUserServiceImpl extends ServiceImpl<HomeUserMapper, HomeUser> implements HomeUserService {

    private static final String SNOWY_SYS_DEFAULT_PASSWORD_KEY = "SNOWY_SYS_DEFAULT_PASSWORD";

    @Resource
    private TransService transService;

    @Resource
    private DevConfigApi devConfigApi;

    @Resource
    private SysUserApi sysUserApi;

    @Resource
    private SysRoleApi sysRoleApi;

    @Resource
    private HomeOrgService homeOrgService;

    @Resource
    private HomePositionService homePositionService;

    @Resource
    private HomeRelationService homeRelationService;

    @Resource
    private HomeMenuService homeMenuService;

    @Resource
    private HomeButtonService homeButtonService;

    @Resource
    private HomeRoleService homeRoleService;

    private List<String> childRoldList = new ArrayList<>();

    @Override
    public Page<HomeUser> page(HomeUserPageParam homeUserPageParam) {
        QueryWrapper<HomeUser> queryWrapper = new QueryWrapper<HomeUser>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(homeUserPageParam.getSearchKey())) {
            queryWrapper.lambda().and(q -> q.like(HomeUser::getAccount, homeUserPageParam.getSearchKey())
                    .or().like(HomeUser::getName, homeUserPageParam.getSearchKey()));
        }
        if (ObjectUtil.isNotEmpty(homeUserPageParam.getOrgId())) {
            List<String> childOrgIdList = CollStreamUtil.toList(homeOrgService.getChildListById(homeOrgService
                    .getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId()), homeUserPageParam.getOrgId(), true), HomeOrg::getId);
            if (ObjectUtil.isNotEmpty(childOrgIdList)) {
                queryWrapper.lambda().in(HomeUser::getOrgId, childOrgIdList);
            } else {
                return new Page<>();
            }
//            queryWrapper.lambda().eq(HomeUser::getOrgId, homeUserPageParam.getOrgId());
        }
        if (ObjectUtil.isNotEmpty(homeUserPageParam.getUserStatus())) {
            queryWrapper.lambda().eq(HomeUser::getUserStatus, homeUserPageParam.getUserStatus());
        }

        if (ObjectUtil.isAllNotEmpty(homeUserPageParam.getSortField(), homeUserPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(homeUserPageParam.getSortOrder());
            queryWrapper.orderBy(true, homeUserPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(homeUserPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(HomeUser::getSortCode);
        }
        // 排除超管
        queryWrapper.lambda().ne(HomeUser::getAccount, HomeBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
        //需要排除自己
        queryWrapper.lambda().ne(HomeUser::getId, StpLoginUserUtil.getLoginUser().getId());

        //需要防越级，只能管理角色级别比自己低的人员，先查出全部角色
        //Mr.wu 加上数据归属，只查询本单位的角色
        List<HomeRole> allRoleList = homeRoleService.list(new LambdaQueryWrapper<HomeRole>().eq(HomeRole::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId()));
        List<String> allRoleIdList = allRoleList.stream().map(HomeRole::getId).collect(Collectors.toList());
        //1、先获取操作员当前角色
        HomeUserIdParam homeUserIdParam = new HomeUserIdParam();
        homeUserIdParam.setId(StpLoginUserUtil.getLoginUser().getId());
        List<String> ownRoleList = this.ownRole(homeUserIdParam);//获取当前用户的角色数组
        List<String> childRoleIds = getChildRole(allRoleList, ownRoleList);//获取下级角色数据
        LambdaQueryWrapper<HomeRelation> relationLambdaQueryWrapperQueryWrapper = new LambdaQueryWrapper<>();

        LambdaQueryWrapper<HomeRelation> allSysRelationQueryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(allRoleIdList)) {
            allSysRelationQueryWrapper.in(HomeRelation::getTargetId, allRoleIdList);//本公司已经授权的用户集合
        }
        List<String> allObjectList = homeRelationService.list(allSysRelationQueryWrapper).stream().map(HomeRelation::getObjectId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(childRoleIds)) {
            relationLambdaQueryWrapperQueryWrapper.select(HomeRelation::getId, HomeRelation::getObjectId, HomeRelation::getTargetId, HomeRelation::getCategory, HomeRelation::getExtJson).in(HomeRelation::getTargetId, childRoleIds).eq(HomeRelation::getCategory, HomeRelationCategoryEnum.SYS_USER_HAS_ROLE.getValue());
            List<String> objectList = homeRelationService.list(relationLambdaQueryWrapperQueryWrapper).stream().map(HomeRelation::getObjectId).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(objectList)) {
                if (ObjectUtil.isNotEmpty(allObjectList)) {
                    queryWrapper.lambda().and(i -> i.in(HomeUser::getId, objectList).or().notIn(HomeUser::getId, allObjectList));//获取未被授权或由当前操作员授权的子用户的用户
                } else {
                    queryWrapper.lambda().and(i -> i.in(HomeUser::getId, objectList));//获取未被授权或由当前操作员授权的子用户的用户
                }
            }
        } else {
            if (ObjectUtil.isNotEmpty(allObjectList)) {
                queryWrapper.lambda().and(i -> i.notIn(HomeUser::getId, allObjectList));//尚未授权的用户信息
            }
        }
        //排序
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.lambda().in(HomeUser::getOrgId, loginUserDataScope);
        } else {
            queryWrapper.lambda().eq(HomeUser::getId, StpUtil.getLoginIdAsString());
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(HomeUserAddParam homeUserAddParam) {
        checkParam(homeUserAddParam);
        HomeUser homeUser = BeanUtil.toBean(homeUserAddParam, HomeUser.class);
        //数据归属
        homeUser.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isEmpty(homeUser.getAvatar())) {
            // 设置默认头像
            homeUser.setAvatar(CommonAvatarUtil.generateImg(homeUser.getName()));
        }
        // 设置密码
        homeUser.setPassword(CommonCryptogramUtil.doHashValue(devConfigApi.getValueByKey(SNOWY_SYS_DEFAULT_PASSWORD_KEY)));
        // 设置状态
        homeUser.setUserStatus(HomeUserStatusEnum.ENABLE.getValue());
        this.save(homeUser);

        // 发布增加事件
        CommonDataChangeEventCenter.doAddWithData(HomeDataTypeEnum.USER.getValue(), JSONUtil.createArray().put(homeUser));
    }

    private void checkParam(HomeUserAddParam homeUserAddParam) {
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(homeUserAddParam.getOrgId())) {
                throw new CommonException("您没有权限在该机构下增加人员，机构id：{}", homeUserAddParam.getOrgId());
            }
        } else {
            throw new CommonException("您没有权限在该机构下增加人员，机构id：{}", homeUserAddParam.getOrgId());
        }
        if (this.count(new LambdaQueryWrapper<HomeUser>()
                .eq(HomeUser::getAccount, homeUserAddParam.getAccount())) > 0) {
            throw new CommonException("存在重复的账号，账号为：{}", homeUserAddParam.getAccount());
        }
        if(ObjectUtil.isNotEmpty(homeUserAddParam.getPhone())) {
            if(!PhoneUtil.isMobile(homeUserAddParam.getPhone())) {
                throw new CommonException("手机号码：{}格式错误", homeUserAddParam.getPhone());
            }
            if (this.count(new LambdaQueryWrapper<HomeUser>()
                    .eq(HomeUser::getPhone, CommonCryptogramUtil.doSm4CbcEncrypt(homeUserAddParam.getPhone()))) > 0) {
                throw new CommonException("存在重复的手机号，手机号为：{}", homeUserAddParam.getPhone());
            }
        }
        if(ObjectUtil.isNotEmpty(homeUserAddParam.getEmail())) {
            if(!CommonEmailUtil.isEmail(homeUserAddParam.getEmail())) {
                throw new CommonException("邮箱：{}格式错误", homeUserAddParam.getEmail());
            }
            if (this.count(new LambdaQueryWrapper<HomeUser>()
                    .eq(HomeUser::getEmail, homeUserAddParam.getEmail())) > 0) {
                throw new CommonException("存在重复的邮箱，邮箱为：{}", homeUserAddParam.getEmail());
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(HomeUserEditParam homeUserEditParam) {
        HomeUser homeUser = this.queryEntity(homeUserEditParam.getId());
        checkParam(homeUserEditParam);
        boolean updateSuperAdminAccount = homeUser.getAccount().equals(HomeBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue()) &&
                !homeUserEditParam.getAccount().equals(HomeBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
        if(updateSuperAdminAccount) {
            throw new CommonException("不可修改系统内置超管人员账号");
        }
        BeanUtil.copyProperties(homeUserEditParam, homeUser);
        this.updateById(homeUser);

        // 发布更新事件
        CommonDataChangeEventCenter.doUpdateWithData(HomeDataTypeEnum.USER.getValue(), JSONUtil.createArray().put(homeUser));
    }

    private void checkParam(HomeUserEditParam homeUserEditParam) {
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(homeUserEditParam.getOrgId())) {
                throw new CommonException("您没有权限编辑该机构下的人员，机构id：{}", homeUserEditParam.getOrgId());
            }
        } else {
            if(!homeUserEditParam.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限编辑该机构下的人员，机构id：{}", homeUserEditParam.getOrgId());
            }
        }
        if (this.count(new LambdaQueryWrapper<HomeUser>()
                .eq(HomeUser::getAccount, homeUserEditParam.getAccount())
                .ne(HomeUser::getId, homeUserEditParam.getId())) > 0) {
            throw new CommonException("存在重复的账号，账号为：{}", homeUserEditParam.getAccount());
        }
        if(ObjectUtil.isNotEmpty(homeUserEditParam.getPhone())) {
            if(!PhoneUtil.isMobile(homeUserEditParam.getPhone())) {
                throw new CommonException("手机号码：{}格式错误", homeUserEditParam.getPhone());
            }
            if (this.count(new LambdaQueryWrapper<HomeUser>()
                    .eq(HomeUser::getPhone, CommonCryptogramUtil.doSm4CbcEncrypt(homeUserEditParam.getPhone()))
                    .ne(HomeUser::getId, homeUserEditParam.getId())) > 0) {
                throw new CommonException("存在重复的手机号，手机号为：{}", homeUserEditParam.getPhone());
            }
        }
        if(ObjectUtil.isNotEmpty(homeUserEditParam.getEmail())) {
            if(!CommonEmailUtil.isEmail(homeUserEditParam.getEmail())) {
                throw new CommonException("邮箱：{}格式错误", homeUserEditParam.getEmail());
            }
            if (this.count(new LambdaQueryWrapper<HomeUser>()
                    .eq(HomeUser::getEmail, homeUserEditParam.getEmail())
                    .ne(HomeUser::getId, homeUserEditParam.getId())) > 0) {
                throw new CommonException("存在重复的邮箱，邮箱为：{}", homeUserEditParam.getEmail());
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<HomeUserIdParam> homeUserIdParamList) {
        List<String> homeUserIdList = CollStreamUtil.toList(homeUserIdParamList, HomeUserIdParam::getId);
        if(ObjectUtil.isNotEmpty(homeUserIdList)) {
            boolean containsSuperAdminAccount = this.listByIds(homeUserIdList).stream().map(HomeUser::getAccount)
                    .collect(Collectors.toSet()).contains(HomeBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
            if(containsSuperAdminAccount) {
                throw new CommonException("不可删除系统内置超管人员");
            }
            // 获取这些人员的的机构id集合
            Set<String> userOrgIdList = this.listByIds(homeUserIdList).stream().map(HomeUser::getOrgId).collect(Collectors.toSet());
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                if(!loginUserDataScope.containsAll(userOrgIdList)) {
                    throw new CommonException("您没有权限删除这些机构下的人员，机构id：{}",
                            CollectionUtil.subtract(userOrgIdList, loginUserDataScope));
                }
            } else {
                if(homeUserIdList.size() != 1 || !homeUserIdList.get(0).equals(StpUtil.getLoginIdAsString())) {
                    throw new CommonException("您没有权限删除这些机构下的人员，机构id：{}", userOrgIdList);
                }
            }
            // 清除【将这些人员作为主管】的信息
            this.update(new LambdaUpdateWrapper<HomeUser>().in(HomeUser::getDirectorId, homeUserIdList).set(HomeUser::getDirectorId, null));

            // 清除【将这些人员作为兼任岗位的主管】的信息
            this.list(new LambdaQueryWrapper<HomeUser>() .isNotNull(HomeUser::getPositionJson)).forEach(homeUser -> {
                List<JSONObject> handledJsonObjectList = JSONUtil.toList(JSONUtil.parseArray(homeUser.getPositionJson()),
                        JSONObject.class).stream().peek(jsonObject -> {
                    String directorId = jsonObject.getStr("directorId");
                    if (ObjectUtil.isNotEmpty(directorId) && homeUserIdList.contains(directorId)) {
                        jsonObject.remove("directorId");
                    }
                }).collect(Collectors.toList());
                this.update(new LambdaUpdateWrapper<HomeUser>().eq(HomeUser::getId, homeUser.getId())
                        .set(HomeUser::getPositionJson, JSONUtil.toJsonStr(handledJsonObjectList)));
            });

            // 清除【将这些人员作为主管】的机构的主管信息
            homeOrgService.update(new LambdaUpdateWrapper<HomeOrg>().in(HomeOrg::getDirectorId, homeUserIdList).set(HomeOrg::getDirectorId, null));

            // 执行删除
            this.removeByIds(homeUserIdList);

            // 发布删除事件
            CommonDataChangeEventCenter.doDeleteWithDataId(HomeDataTypeEnum.USER.getValue(), homeUserIdList);
        }
    }

    @Override
    public HomeUser detail(HomeUserIdParam homeUserIdParam) {
        return this.queryEntity(homeUserIdParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void disableUser(HomeUserIdParam homeUserIdParam) {
        HomeUser homeUser = this.detail(homeUserIdParam);
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(homeUser.getOrgId())) {
                throw new CommonException("您没有权限禁用该机构下的人员：{}，机构id：{}", homeUser.getName(), homeUser.getOrgId());
            }
        } else {
            if(!homeUser.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限禁用该机构下的人员：{}，机构id：{}", homeUser.getName(), homeUser.getOrgId());
            }
        }
        this.update(new LambdaUpdateWrapper<HomeUser>().eq(HomeUser::getId,
                homeUserIdParam.getId()).set(HomeUser::getUserStatus, HomeUserStatusEnum.DISABLED.getValue()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void enableUser(HomeUserIdParam homeUserIdParam) {
        HomeUser homeUser = this.detail(homeUserIdParam);
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(homeUser.getOrgId())) {
                throw new CommonException("您没有权限启用该机构下的人员：{}，机构id：{}", homeUser.getName(), homeUser.getOrgId());
            }
        } else {
            if(!homeUser.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限启用该机构下的人员：{}，机构id：{}", homeUser.getName(), homeUser.getOrgId());
            }
        }
        this.update(new LambdaUpdateWrapper<HomeUser>().eq(HomeUser::getId,
                homeUserIdParam.getId()).set(HomeUser::getUserStatus, HomeUserStatusEnum.ENABLE.getValue()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void resetPassword(HomeUserIdParam homeUserIdParam) {
        HomeUser homeUser = this.detail(homeUserIdParam);
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(homeUser.getOrgId())) {
                throw new CommonException("您没有权限为该机构下的人员：{}重置密码，机构id：{}", homeUser.getName(), homeUser.getOrgId());
            }
        } else {
            if(!homeUser.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限为该机构下的人员：{}重置密码，机构id：{}", homeUser.getName(), homeUser.getOrgId());
            }
        }
        this.update(new LambdaUpdateWrapper<HomeUser>().eq(HomeUser::getId,
                homeUserIdParam.getId()).set(HomeUser::getPassword,
                CommonCryptogramUtil.doHashValue(devConfigApi.getValueByKey(SNOWY_SYS_DEFAULT_PASSWORD_KEY))));
    }

    @Override
    public List<String> ownRole(HomeUserIdParam homeUserIdParam) {
        return sysUserApi.ownRole(homeUserIdParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void grantRole(HomeUserGrantRoleParam homeUserGrantRoleParam) {
        HomeUser homeUser = this.queryEntity(homeUserGrantRoleParam.getId());
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
            if(!loginUserDataScope.contains(homeUser.getOrgId())) {
                throw new CommonException("您没有权限为该机构下的人员：{}授权角色，机构id：{}", homeUser.getName(), homeUser.getOrgId());
            }
        } else {
            if(!homeUser.getId().equals(StpUtil.getLoginIdAsString())) {
                throw new CommonException("您没有权限为该机构下的人员：{}授权角色，机构id：{}", homeUser.getName(), homeUser.getOrgId());
            }
        }
        sysUserApi.grantRole(homeUserGrantRoleParam.getId(), homeUserGrantRoleParam.getRoleIdList());
    }

    @Override
    public HomeUserOwnResourceResult ownResource(HomeUserIdParam homeUserIdParam) {
        HomeUserOwnResourceResult homeUserOwnResourceResult = new HomeUserOwnResourceResult();
        homeUserOwnResourceResult.setId(homeUserIdParam.getId());
        homeUserOwnResourceResult.setGrantInfoList(homeRelationService.getRelationListByObjectIdAndCategory(homeUserIdParam.getId(),
                HomeRelationCategoryEnum.SYS_USER_HAS_RESOURCE.getValue()).stream().map(sysRelation ->
                JSONUtil.toBean(sysRelation.getExtJson(), HomeUserOwnResourceResult.HomeUserOwnResource.class)).collect(Collectors.toList()));
        return homeUserOwnResourceResult;
    }

    @Override
    public void grantResource(HomeUserGrantResourceParam homeUserGrantResourceParam) {
        List<String> menuIdList = homeUserGrantResourceParam.getGrantInfoList().stream()
                .map(HomeUserGrantResourceParam.HomeUserGrantResource::getMenuId).collect(Collectors.toList());
//        if(ObjectUtil.isNotEmpty(menuIdList)) {
//            HomeUserIdParam homeUserIdParam = new HomeUserIdParam();
//            homeUserIdParam.setId(sysUserGrantResourceParam.getId());
//            List<String> roleIdList = this.ownRole(homeUserIdParam);
//            Set<String> sysModuleIdList = sysMenuService.listByIds(menuIdList).stream().map(SysMenu::getModule).collect(Collectors.toSet());
//            boolean containsSystemModule = sysModuleService.listByIds(sysModuleIdList).stream().map(SysModule::getCode)
//                .collect(Collectors.toSet()).contains(SysBuildInEnum.BUILD_IN_MODULE_CODE.getValue());
//            if(containsSystemModule) {
//                if(ObjectUtil.isEmpty(roleIdList)) {
//                    throw new CommonException("非超管角色用户不可被授权系统模块菜单资源");
//                } else {
//                    boolean hasSuperAdminRole = sysRoleService.listByIds(roleIdList).stream().map(SysRole::getCode).collect(Collectors.toSet())
//                        .contains(SysBuildInEnum.BUILD_IN_ROLE_CODE.getValue());
//                    if(!hasSuperAdminRole) {
//                        throw new CommonException("非超管角色用户不可被授权系统模块菜单资源");
//                    }
//                }
//            }
//        }
        List<String> extJsonList = homeUserGrantResourceParam.getGrantInfoList().stream()
                .map(JSONUtil::toJsonStr).collect(Collectors.toList());
        //提取menu对应的page权限字符
        List<String> targetList = new ArrayList<>();
        menuIdList.forEach(menuId->{
            HomeMenu homeMenu = homeMenuService.queryEntity(menuId);
            if(ObjectUtil.isNotEmpty(homeMenu.getCode())) {
                List<String> codes = List.of(homeMenu.getCode().split(","));
                codes.forEach(code ->{
                    if(ObjectUtil.isNotEmpty(homeMenu.getPath()) && !targetList.contains(code)){
                        targetList.add("/" + code);
                    }
                });
            }
        });
        //提取按钮对应的权限字符串
        homeUserGrantResourceParam.getGrantInfoList().stream().map(HomeUserGrantResourceParam.HomeUserGrantResource::getButtonInfo).forEach((List<String> buttonList)->{
            buttonList.stream().forEach((String buttonId)->{
                HomeButton homeButton = homeButtonService.queryEntity(buttonId);
                if(ObjectUtil.isNotEmpty(homeButton.getComponent())) {
                    List<String> components = List.of(homeButton.getComponent().split(","));
                    components.forEach(component -> {
                        if (ObjectUtil.isNotEmpty(component) && !targetList.contains("/" + component)) {
                            targetList.add("/" + component);
                        }
                    });
                }
                //20241218改支持多个后端权限
//                if(ObjectUtil.isNotEmpty(sysButtonService.queryEntity(buttonId).getComponent()) && !targetList.contains("/"+sysButtonService.queryEntity(buttonId).getComponent())){
//                    targetList.add("/"+sysButtonService.queryEntity(buttonId).getComponent());
//                }
            });
        });
        List<String> extJsonListP = new ArrayList<>();
        targetList.forEach(menuAndButtonId->{
            JSONObject ext = new JSONObject();
            List<String> orgList = new ArrayList<>();
            ext.set("apiUrl",menuAndButtonId);
            ext.set("scopeCategory","SCOPE_ALL");
            ext.set("scopeDefineOrgIdList",orgList);
            extJsonListP.add(ext.toString());
        });

        homeRelationService.saveRelationBatchWithClear(homeUserGrantResourceParam.getId(), menuIdList, HomeRelationCategoryEnum.SYS_USER_HAS_RESOURCE.getValue(), extJsonList);
        homeRelationService.saveRelationBatchWithClear(homeUserGrantResourceParam.getId(), targetList, HomeRelationCategoryEnum.SYS_USER_HAS_PERMISSION.getValue(),
                extJsonListP);//保存后端权限
    }

    @Override
    public void exportUser(HomeUserExportParam homeUserExportParam, HttpServletResponse response) throws IOException {
        File tempFile = null;
        try {
            QueryWrapper<HomeUser> queryWrapper = new QueryWrapper<HomeUser>().checkSqlInjection();
            // 排除超管
            queryWrapper.lambda().ne(HomeUser::getAccount, HomeBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
            // 校验数据范围
            List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
            if(ObjectUtil.isNotEmpty(loginUserDataScope)) {
                queryWrapper.lambda().in(HomeUser::getOrgId, loginUserDataScope);
            } else {
                queryWrapper.lambda().eq(HomeUser::getId, StpUtil.getLoginIdAsString());
            }
            if(ObjectUtil.isNotEmpty(homeUserExportParam.getUserIds())) {
                queryWrapper.lambda().in(HomeUser::getId, StrUtil.split(homeUserExportParam.getUserIds(), StrUtil.COMMA));
            } else {
                if (ObjectUtil.isNotEmpty(homeUserExportParam.getSearchKey())) {
                    queryWrapper.lambda().and(q -> q.like(HomeUser::getAccount, homeUserExportParam.getSearchKey())
                            .or().like(HomeUser::getName, homeUserExportParam.getSearchKey())
                            .or().like(HomeUser::getPhone, homeUserExportParam.getSearchKey()));
                }
                if (ObjectUtil.isNotEmpty(homeUserExportParam.getUserStatus())) {
                    queryWrapper.lambda().eq(HomeUser::getUserStatus, homeUserExportParam.getUserStatus());
                }
            }
            String fileName = "SNOWY系统B端人员信息清单.xlsx";
            List<HomeUser> homeUserList = this.list(queryWrapper);
            if(ObjectUtil.isEmpty(homeUserList)) {
                throw new CommonException("无数据可导出");
            }
            transService.transBatch(homeUserList);
            homeUserList = CollectionUtil.sort(homeUserList, Comparator.comparing(HomeUser::getOrgId));
            List<HomeUserExportResult> homeUserExportResultList = homeUserList.stream()
                    .map(homeUser -> {
                        HomeUserExportResult homeUserExportResult = new HomeUserExportResult();
                        BeanUtil.copyProperties(homeUser, homeUserExportResult);
                        homeUserExportResult.setGroupName(ObjectUtil.isNotEmpty(homeUserExportResult.getOrgName())?
                                homeUserExportResult.getOrgName():"无组织");
                        // 状态枚举转为文字
                        homeUserExportResult.setUserStatus(homeUserExportResult.getUserStatus()
                                .equalsIgnoreCase(HomeUserStatusEnum.ENABLE.getValue())?"正常":"停用");
                        // 将base64转为byte数组
                        if (ObjectUtil.isNotEmpty(homeUser.getAvatar())) {
                            homeUserExportResult.setAvatar(ImgUtil.toBytes(ImgUtil.toImage(StrUtil
                                    .split(homeUser.getAvatar(), StrUtil.COMMA).get(1)), ImgUtil.IMAGE_TYPE_PNG));
                        }
                        return homeUserExportResult;
                    }).collect(Collectors.toList());
            // 创建临时文件
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);

            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 14);
            headWriteCellStyle.setWriteFont(headWriteFont);
            // 水平垂直居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
            contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            // 内容背景白色
            contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            WriteFont contentWriteFont = new WriteFont();

            // 内容字体大小
            contentWriteFont.setFontHeightInPoints((short) 12);
            contentWriteCellStyle.setWriteFont(contentWriteFont);

            //设置边框样式，细实线
            contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
            contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
            contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
            contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

            // 水平垂直居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle,
                    contentWriteCellStyle);

            // 写excel
            EasyExcel.write(tempFile.getPath(), HomeUserExportResult.class)
                    // 自定义样式
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    // 自动列宽
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    // 机构分组合并单元格
                    .registerWriteHandler(new CommonExcelCustomMergeStrategy(homeUserExportResultList.stream().map(HomeUserExportResult::getGroupName)
                            .collect(Collectors.toList()), 0))
                    // 设置第一行字体
                    .registerWriteHandler(new CellWriteHandler() {
                        @Override
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            WriteCellData<?> cellData = context.getFirstCellData();
                            WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                            Integer rowIndex = context.getRowIndex();
                            if(rowIndex == 0) {
                                WriteFont headWriteFont = new WriteFont();
                                headWriteFont.setFontName("宋体");
                                headWriteFont.setBold(true);
                                headWriteFont.setFontHeightInPoints((short) 16);
                                writeCellStyle.setWriteFont(headWriteFont);
                            }
                        }
                    })
                    // 设置表头行高
                    .registerWriteHandler(new AbstractRowHeightStyleStrategy() {
                        @Override
                        protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
                            if(relativeRowIndex == 0) {
                                // 表头第一行
                                row.setHeightInPoints(34);
                            } else {
                                // 表头其他行
                                row.setHeightInPoints(30);
                            }
                        }
                        @Override
                        protected void setContentColumnHeight(Row row, int relativeRowIndex) {
                            // 内容行
                            row.setHeightInPoints(20);
                        }
                    })
                    .sheet("人员信息")
                    .doWrite(homeUserExportResultList);
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            log.error(">>> 人员导出异常：", e);
            CommonResponseUtil.renderError(response, "导出失败");
        } finally {
            FileUtil.del(tempFile);
        }
    }

    @Override
    public void exportUserInfo(HomeUserIdParam homeUserIdParam, HttpServletResponse response) throws IOException {
        File destTemplateFile = null;
        File resultFile = null;
        try {
            HomeUser homeUser = this.queryEntity(homeUserIdParam.getId());
            transService.transOne(homeUser);
            // 读取模板流
            InputStream inputStream = POICacheManager.getFile("userExportTemplate.docx");
            // 创建一个临时模板
            destTemplateFile = FileUtil.writeFromStream(inputStream, FileUtil.file(FileUtil.getTmpDir() +
                    File.separator + "userExportTemplate.docx"));
            // 构造填充的参数
            Map<String, Object> map = BeanUtil.beanToMap(homeUser);
            String avatarBase64;
            if(ObjectUtil.isNotEmpty(homeUser.getAvatar())) {
                avatarBase64 = homeUser.getAvatar();
            } else {
                avatarBase64 = CommonAvatarUtil.generateImg(homeUser.getName());
            }
            // 头像
            ImageEntity imageEntity = new ImageEntity(ImgUtil.toBytes(ImgUtil.toImage(StrUtil
                    .split(avatarBase64, StrUtil.COMMA).get(1)), ImgUtil.IMAGE_TYPE_PNG), 120, 160);
            map.put("avatar", imageEntity);
            if(ObjectUtil.isNotEmpty(homeUser.getBirthday())) {
                try {
                    // 年龄
                    long age = DateUtil.betweenYear(DateUtil.parseDate(homeUser.getBirthday()), DateTime.now(), true);
                    if(age != 0) {
                        map.put("age", age + "岁");
                    }
                } catch (Exception ignored) {
                }
            }
            // 导出时间
            map.put("exportDateTime", DateUtil.format(DateTime.now(), DatePattern.CHINESE_DATE_PATTERN));
            // 生成doc
            XWPFDocument doc = WordExportUtil.exportWord07(destTemplateFile.getAbsolutePath(), map);
            // 生成临时导出文件
            resultFile = FileUtil.file(FileUtil.getTmpDir() + File.separator + "SNOWY系统B端人员信息_" + homeUser.getName() + ".docx");
            // 写入
            BufferedOutputStream outputStream = FileUtil.getOutputStream(resultFile);
            doc.write(outputStream);
            outputStream.close();
            // 下载
            CommonDownloadUtil.download(resultFile, response);
        } catch (Exception e) {
            log.error(">>> 导出人员个人信息异常：", e);
            CommonResponseUtil.renderError(response, "导出失败");
        } finally {
            // 删除临时文件
            if(ObjectUtil.isNotEmpty(destTemplateFile)) {
                FileUtil.del(destTemplateFile);
            }
            if(ObjectUtil.isNotEmpty(resultFile)) {
                FileUtil.del(resultFile);
            }
        }
    }

    @Override
    public HomeUser queryEntity(String id) {
        HomeUser homeUser = this.getById(id);
        if(ObjectUtil.isEmpty(homeUser)) {
            throw new CommonException("人员不存在，id值为：{}", id);
        }
        return homeUser;
    }

    //循环的方法获取子角色列表
    public List<String> getChildRole(List<HomeRole> roleList, List<String> parentRoleIds) {
        List<String> childRoldList = CollectionUtil.newArrayList();
        List<HomeRole> newRoles = CollectionUtil.newArrayList();
        do {
            newRoles = roleList.stream().filter((item) -> {
                return parentRoleIds.contains(item.getParentId());
            }).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(newRoles)) {
                List<String> newRoleIds = new ArrayList<>();
                for (HomeRole homeRole : newRoles) {
                    newRoleIds.add(homeRole.getId());
                }
                childRoldList.addAll(newRoleIds);
                parentRoleIds.clear();
                parentRoleIds.addAll(newRoleIds);
            }
        } while (ObjectUtil.isNotEmpty(newRoles));
        if (ObjectUtil.isNotEmpty(childRoldList)) {
            return childRoldList;
        } else {
            return new ArrayList<>();
        }

    }

    /* ====人员部分所需要用到的选择器==== */

    @Override
    public List<Tree<String>> orgTreeSelector() {
        LambdaQueryWrapper<HomeOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        // 定义机构集合
        Set<HomeOrg> homeOrgSet = CollectionUtil.newHashSet();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            // 获取所有机构
            List<HomeOrg> allOrgList = homeOrgService.list();
            loginUserDataScope.forEach(orgId -> homeOrgSet.addAll(homeOrgService.getParentListById(allOrgList, orgId, true)));
            List<String> loginUserDataScopeFullList = homeOrgSet.stream().map(HomeOrg::getId).collect(Collectors.toList());
            lambdaQueryWrapper.in(HomeOrg::getId, loginUserDataScopeFullList);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(HomeOrg::getSortCode);
        List<HomeOrg> homeOrgList = homeOrgService.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = homeOrgList.stream().map(homeOrg ->
                        new TreeNode<>(homeOrg.getId(), homeOrg.getParentId(), homeOrg.getName(), homeOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public Page<HomeOrg> orgListSelector(HomeUserSelectorOrgListParam homeUserSelectorOrgListParam) {
        LambdaQueryWrapper<HomeOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(HomeOrg::getId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 查询部分字段
        lambdaQueryWrapper.select(HomeOrg::getId, HomeOrg::getParentId, HomeOrg::getName,
                HomeOrg::getCategory, HomeOrg::getSortCode);
        if (ObjectUtil.isNotEmpty(homeUserSelectorOrgListParam.getParentId())) {
            lambdaQueryWrapper.eq(HomeOrg::getParentId, homeUserSelectorOrgListParam.getParentId());
        }
        if (ObjectUtil.isNotEmpty(homeUserSelectorOrgListParam.getSearchKey())) {
            lambdaQueryWrapper.like(HomeOrg::getName, homeUserSelectorOrgListParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(HomeOrg::getSortCode);
        return homeOrgService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }

    @Override
    public Page<HomePosition> positionSelector(HomeUserSelectorPositionParam homeUserSelectorPositionParam) {
        LambdaQueryWrapper<HomePosition> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(HomePosition::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 查询部分字段
        lambdaQueryWrapper.select(HomePosition::getId, HomePosition::getOrgId, HomePosition::getName,
                HomePosition::getCategory, HomePosition::getSortCode);
        if (ObjectUtil.isNotEmpty(homeUserSelectorPositionParam.getOrgId())) {
            lambdaQueryWrapper.eq(HomePosition::getOrgId, homeUserSelectorPositionParam.getOrgId());
        }
        if (ObjectUtil.isNotEmpty(homeUserSelectorPositionParam.getSearchKey())) {
            lambdaQueryWrapper.like(HomePosition::getName, homeUserSelectorPositionParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(HomePosition::getSortCode);
        return homePositionService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }

    @SuppressWarnings("ALL")
    @Override
    public Page<HomeUserRoleResult> roleSelector(HomeUserSelectorRoleParam homeUserSelectorRoleParam) {
        //20250218 Mr.wu 修改人员管理中授权角色的角色选择器获取逻辑，原逻辑是按部门归属的角色进行上下级过滤，现改为根据创建者父子关系获取下级角色
        LambdaQueryWrapper<HomeRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询部分字段
        lambdaQueryWrapper.select(HomeRole::getId, HomeRole::getOrgId, HomeRole::getName,
                HomeRole::getCategory, HomeRole::getSortCode);
        //在此加入上下级过滤判断，即只显示由当前用户角色所创建的下级及子孙级角色，不显示自已的以及自己以上的
        //获取公司全部角色
        List<HomeRole> allRoleList = homeRoleService.list();
        //1、先获取操作员当前角色
        HomeUserIdParam homeUserIdParam = new HomeUserIdParam();
        homeUserIdParam.setId(StpLoginUserUtil.getLoginUser().getId());
        List<String> ownRoleList = this.ownRole(homeUserIdParam);//获取当前用户的角色数组
        childRoldList = new ArrayList<>();
        List<String> childRoleIds =  getChildRole(allRoleList, ownRoleList);//获取下级角色数据
        if(ObjectUtil.isNotEmpty(childRoleIds)){
            lambdaQueryWrapper.in(HomeRole::getId,childRoleIds);
            return BeanUtil.toBean(homeRoleService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper), Page.class);
        }else{
            return new Page<>();
        }
    }

    @Override
    public Page<HomeUser> userSelector(HomeUserSelectorUserParam homeUserSelectorUserParam) {
        LambdaQueryWrapper<HomeUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(HomeUser::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 只查询部分字段
        lambdaQueryWrapper.select(HomeUser::getId, HomeUser::getAvatar, HomeUser::getOrgId, HomeUser::getPositionId, HomeUser::getAccount,
                HomeUser::getName, HomeUser::getSortCode, HomeUser::getGender, HomeUser::getEntryDate);
        if (ObjectUtil.isNotEmpty(homeUserSelectorUserParam.getOrgId())) {
            // 如果机构id不为空，则查询该机构及其子机构下的所有人
            List<String> childOrgIdList = CollStreamUtil.toList(homeOrgService.getChildListById(homeOrgService
                    .getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId()), homeUserSelectorUserParam.getOrgId(), true), HomeOrg::getId);
            if (ObjectUtil.isNotEmpty(childOrgIdList)) {
                lambdaQueryWrapper.in(HomeUser::getOrgId, childOrgIdList);
            } else {
                return new Page<>();
            }
        }
        // 排除超管
        lambdaQueryWrapper.ne(HomeUser::getAccount, HomeBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
        if (ObjectUtil.isNotEmpty(homeUserSelectorUserParam.getSearchKey())) {
            lambdaQueryWrapper.like(HomeUser::getName, homeUserSelectorUserParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(HomeUser::getSortCode);
        return this.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }
}
